package com.demarc.pesquisas.web.validator;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.apache.commons.lang3.StringUtils;

import com.demarc.pesquisas.infraestrutura.mensagem.MensagemJsfUtils;
import com.demarc.pesquisas.infraestrutura.web.jsf.JsfUtil;
import com.demarc.pesquisas.negocio.util.ValidacaoUtils;

@FacesValidator(value = "CPFValidator")
public class CPFValidator implements Validator, Serializable {

	public static final String CPF_MESSAGE_ID = "com.demarc.pesquisas.web.validator.CPFValidator.CPF";

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object objectValue) throws ValidatorException {

		if (objectValue != null
				&& StringUtils.isNotEmpty(objectValue.toString())) {

			String cpf = (String) objectValue;
			if (!ValidacaoUtils.isCpfValido(cpf)) {
				FacesMessage facesMessage = MensagemJsfUtils.criarFacesMessage(
						FacesMessage.SEVERITY_ERROR, CPF_MESSAGE_ID,
						JsfUtil.getLabel(context, component));
				throw new ValidatorException(facesMessage);
			}
		}
	}
}